package com.stox.services.screener.manager;

import java.util.ArrayList;
import java.util.List;

import com.stox.services.screener.model.intf.Screen;
import com.stox.services.screener.model.intf.ScreenConfiguration;
import com.stox.services.screener.util.ScanRegistry;
import com.stox.shared.core.beans.BeanDescriptor;
import com.stox.shared.screener.model.ScreenBeanDescriptor;
import com.stox.shared.screener.model.ScreenerConfiguration;

@SuppressWarnings({"rawtypes","unchecked"})
public class ScreenerManager {
	
	public static final ScreenerManager INSTANCE = new ScreenerManager();

	private final List<ScreenBeanDescriptor> screenBeanDescriptors = new ArrayList<>();
	
	private ScreenerManager() {
		
	}
	
	public List<ScreenBeanDescriptor> findAll(){
		if(screenBeanDescriptors.isEmpty()){
			for(Screen screen : Screen.ALL){
				screenBeanDescriptors.add(screen.getScreenBeanDescriptor());
			}
		}
		return screenBeanDescriptors;
	}
	
	public void start(final String scanId,final ScreenerConfiguration screenerConfiguration,final ScreenBeanDescriptor screenBeanDescriptor) {
		for(final Screen screen : Screen.ALL){
			if(screenBeanDescriptor.getKey().equalsIgnoreCase(screen.getKey())){
				new Thread(){
					public void run() {
						screen.screen(scanId, screenerConfiguration, (ScreenConfiguration)screenBeanDescriptor.createBean());
					};
				}.start();
				break;
			}
		}
	}

	
	public double completionPercentage(String scanId) {
		return ScanRegistry.findOne(scanId).getCompletionPercentage();
	}
	
	public void cancel(String scanId){
		ScanRegistry.findOne(scanId).cancel();
	}
	
	
	public List<BeanDescriptor> getMatches(String scanId) {
		List<?> matches = ScanRegistry.findOne(scanId).getUnServedMatches();
		List<BeanDescriptor> beanDescriptors = new ArrayList<>(matches.size());
		for(Object match : matches){
			beanDescriptors.add(new BeanDescriptor(match));
		}
		return beanDescriptors;
	}
	
	
}
